import { Modal, message } from "ant-design-vue";
import { computed, createVNode, h } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { deleteDepartApi, deleteUserApi, disabledUserApi, enabledUserApi, getListApi, resetUserPasswordApi } from "@/api/managementCenter/departmentPersonnel";

export default function OperationHook(state: Base.GeneraDataType) {
  const { dialogOpts, searchForm, tableRef, tableData, loading, expandedKeys, autoExpandParent, getDeptTree, drawerOpts } = state;
  const selectRows = computed<Array<DepartmentPersonnel.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });

  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };
  const getData = () => {
    const params = {
      ...searchForm
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => (loading.value = false));
  };
  const addHandle = () => {
    dialogOpts.title = "新增用户";
    dialogOpts.width = "520px";
    dialogOpts.component = "AddUser";
    dialogOpts.type = 1;
    dialogOpts.visible = true;
  };
  const editHandle = (row: DepartmentPersonnel.ListRows) => {
    dialogOpts.title = "编辑用户";
    dialogOpts.width = "520px";
    dialogOpts.component = "AddUser";
    dialogOpts.type = 2;
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };
  const removeHandle = (row: DepartmentPersonnel.ListRows) => {
    Modal.confirm({
      title: `正在进行删除用户（${row.username}）操作，请再次确认?`,
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        deleteUserApi({ id: row.id }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };
  const changeStatusHandle = (row: DepartmentPersonnel.ListRows) => {
    const params: any = {
      id: row.id
    };
    let tip = null,
      requestFn: any = null;
    if (row.status === 1) {
      tip = "是否停用该用户?";
      requestFn = disabledUserApi;
    } else {
      tip = "是否启用该用户?";
      requestFn = enabledUserApi;
    }
    Modal.confirm({
      title: tip,
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        requestFn(params).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getData();
          }
        });
      }
    });
  };
  const importFileHandle = () => {
    dialogOpts.title = "导入";
    dialogOpts.width = "520px";
    dialogOpts.component = "ImportUser";
    dialogOpts.type = 1;
    dialogOpts.visible = true;
  };
  const batchModifyDepartHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选用户!");
    dialogOpts.title = "批量修改部门";
    dialogOpts.width = "520px";
    dialogOpts.passData = selectRows.value;
    dialogOpts.component = "BatchModifyDepart";
    dialogOpts.visible = true;
  };
  const setSupervisorHandle = (row: DepartmentPersonnel.ListRows) => {
    dialogOpts.title = "设置主管";
    dialogOpts.width = "520px";
    dialogOpts.passData = row;
    dialogOpts.component = "SetSupervisor";
    dialogOpts.visible = true;
  };
  // 新建下级部门
  const addNextDepartHandle = (row: DepartmentPersonnel.ListRows) => {
    dialogOpts.title = "新建下级部门";
    dialogOpts.width = "520px";
    dialogOpts.passData = row;
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyDepartment";
    dialogOpts.visible = true;
  };
  // 新建同级部门
  const addEquativeDepartHandle = (row: DepartmentPersonnel.ListRows) => {
    if (String(row.pid) === "0") {
      drawerOpts.title = "新建公司信息";
      drawerOpts.width = "1000px";
      drawerOpts.passData = row;
      drawerOpts.type = 2;
      drawerOpts.component = "CompanyInfo";
      drawerOpts.visible = true;
    } else {
      dialogOpts.title = "新建同级部门";
      dialogOpts.width = "520px";
      dialogOpts.passData = row;
      dialogOpts.type = 2;
      dialogOpts.component = "ModifyDepartment";
      dialogOpts.visible = true;
    }
  };
  // 修改部门名称
  const modifyDepartHandle = (row: DepartmentPersonnel.ListRows) => {
    dialogOpts.title = "修改部门名称";
    dialogOpts.width = "520px";
    dialogOpts.passData = row;
    dialogOpts.type = 3;
    dialogOpts.component = "ModifyDepartment";
    dialogOpts.visible = true;
  };
  const changeCompanyInfoHandle = (row: DepartmentPersonnel.ListRows) => {
    drawerOpts.title = "编辑公司信息";
    drawerOpts.width = "1000px";
    drawerOpts.passData = row;
    drawerOpts.type = 1;
    drawerOpts.component = "CompanyInfo";
    drawerOpts.visible = true;
  };
  const deleteDepartmentHandle = (row: DepartmentPersonnel.ListRows) => {
    Modal.confirm({
      title: `正在进行删除${row.pid === "0" ? "公司" : "部门"}操作，请再次确认?`,
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        console.log("OK", row);
        deleteDepartApi({ id: row.id }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            getDeptTree();
            getData();
          }
        });
      }
    });
  };
  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  };
  const selectDepartHandle = (selectedKeys: Array<string>) => {
    if (selectedKeys.length) searchForm.deptId = selectedKeys[0];
    else searchForm.deptId = "0";
    getData();
  };
  const dialogSubmitHandle = () => {
    dialogOpts.visible = false;
    getDeptTree();
    getData();
  };

  //重置密码
  const restUserPasswordHandle = (row: CustomerManagement.ListRows) => {
    Modal.confirm({
      title: h("div", { style: { display: "flex", justifyContent: "center", flexDirection: "column" } }, [h("p", "是否重置密码?确认后将退出登录"), h("p", "重置密码:123456")]),
      icon: createVNode(ExclamationCircleOutlined),
      content: "",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      async onOk() {
        const restPassword: any = await resetUserPasswordApi({ id: row.id, password: "123456" });
        const { code } = restPassword;
        if (code === 200) {
          message.success("操作成功");
          getData();
          //退出登录
          // const logOut: any = await loginOutApi();
          // if (logOut.code === 200) {
          //   clearAuthent();
          //   PermissionStore.asyncRoutes = [];
          //   PermissionStore.clearCacheList();
          //   resetRouter();
          //   router.replace("/login");
          // }
        }
      }
    });
  };

  return {
    searchHandle,
    getData,
    dialogSubmitHandle,
    addHandle,
    editHandle,
    removeHandle,
    changeStatusHandle,
    importFileHandle,
    batchModifyDepartHandle,
    setSupervisorHandle,
    addNextDepartHandle,
    addEquativeDepartHandle,
    modifyDepartHandle,
    deleteDepartmentHandle,
    onExpand,
    selectDepartHandle,
    changeCompanyInfoHandle,
    restUserPasswordHandle
  };
}
